Here is the code. The program is very simple, a book shop - in admin mode we need add books as in client mode we can subscribe them. I want to do this program using dynamic memory allocation not array of objects.
Code:
/*Sarath*/
#include<iostream.h>
#include<conio.h>
class bookshop;
bookshop *start,*temp,*ptr;
class bookshop //self referential class to define a bookshop
{
char title[20]; //to store book title
char author[20]; //to store author name
float price; //price of the book
int copies; //no: of copies
public:
class bookshop *next; //to point to node of same class
public:
bookshop(bookshop *);
void admin(); //to enter new stock
void client(); //to search and purchase
void display(); //to display book details
};
bookshop::bookshop(bookshop *temp) //parametrised constructor
{ //to insert new node
if(start==NULL)
{
start=temp;
start->next=NULL;
}
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=temp;
temp->next=NULL;
}
}
void main()
{
int choice;
start=NULL;
clrscr();
do
{
cout<<"\n\n\tBook Shop\n";
cout<<"\n\t1. Admin\n\t2. Client\n\t3. Quit";
cout<<"\n\n\tChoice: ";
cin>>choice;
bookshop *temp=new bookshop(temp);
switch(choice)
{
case 1:
temp->admin();
break;
case 2:
temp->client();
delete temp; //to delete last node
break;
case 3:
cout<<"\n\tPress any key to quit..";
break;
default:
cout<<"\nInvalid choice!\n";
}
}while(choice!=3);
getch();
}
void bookshop::admin()
{
cout<<"\n\tBook title: ";
cin>>title;
cout<<"\n\tAuthor: ";
cin>>author;
cout<<"\n\tPrice: ";
cin>>price;
cout<<"\n\tNo of copiess: ";
cin>>copies;
display();
}
void bookshop::client()
{
start->display();
int flag=0;
cout<<"\n\tTitle?:";
cin>>title;
cout<<start;
ptr=start;
while(ptr->next!=NULL)
{
if(ptr->title==title)
{
ptr->display();
flag=1;
break;
}
ptr=ptr->next;
}
if(flag==0)
cout<<"\n\n\t"<<title<<" is not available!";
}
void bookshop::display()
{
cout<<"\n\n\t"<<title<<" is available";
cout<<"\n\tAuthor: "<<author;
cout<<"\n\tPrice: "<<price;
ptr=start;
while(ptr!=NULL) {
cout<<" "<<ptr->title; ptr=ptr->next;}
}